/**业务管理流程平台版本1.0,生成时间:2017-04-13 13:16:48**/
package com.xbdun.service.bmp.service.system.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.xbdun.common.api.Client;
import com.xbdun.common.enums.UserRolesEnums;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.dao.bmp.dto.MenuNodeDto;
import com.xbdun.dao.bmp.dto.MenuPlatDto;
import com.xbdun.dao.bmp.dto.PlatformInfoDto;
import com.xbdun.dao.bmp.entity.XbdunSysMenuDo;
import com.xbdun.dao.bmp.mapper.SysMenuMapper;
import com.xbdun.facade.bmp.enumx.SysMenuEnum.SysMenuTypeEnum;
import com.xbdun.facade.bmp.exceptions.BmpBizException;
import com.xbdun.facade.bmp.request.system.SysMenuRequest;
import com.xbdun.facade.bmp.response.system.PlatResponse;
import com.xbdun.facade.bmp.response.system.SysMenuResponse;
import com.xbdun.facade.bmp.response.system.TreeNodeResponse;
import com.xbdun.service.bmp.biz.SysMenuBiz;
import com.xbdun.service.bmp.biz.SysOrgBiz;
import com.xbdun.service.bmp.service.system.SysMenuService;

import lombok.extern.slf4j.Slf4j;

/**
 * 菜单管理
 * 
 * @ClassName SysMenuServiceImpl
 * @author 张国涛 @2017-04-13 13:16:48
 */
@Service
@Slf4j
public class SysMenuServiceImpl implements SysMenuService {
	@Autowired
	private SysMenuMapper sysMenuMapper;
	@Autowired
	private SysMenuBiz sysMenuBiz;
	@Autowired
	private SysOrgBiz sysOrgBiz;
	private Object obj = new Object();
	/**
	 * 新增平台菜单
	 * 
	 * @param request
	 */
	@SuppressWarnings("unused")
	@Transactional
	public Long addSysMenu(SysMenuRequest request) throws Exception {

		XbdunSysMenuDo xbdunSysMenuDo = new XbdunSysMenuDo();
		BeanUtils.copyProperties(xbdunSysMenuDo, request);
		
		log.info("新增菜单,{}",JSON.toJSONString(xbdunSysMenuDo));
		Long addXbdunSysMenuInfo = null;
		synchronized (obj) {
			//类型: 目录【1】，页面【2】，按钮【3】
			xbdunSysMenuDo.setMenuType(1);
			if(StringUtils.isNotBlank(xbdunSysMenuDo.getUrl())){
				xbdunSysMenuDo.setMenuType(2);
			}
			addXbdunSysMenuInfo = sysMenuBiz.addXbdunSysMenu(xbdunSysMenuDo,request.getPlatCode());
			if (null == addXbdunSysMenuInfo || addXbdunSysMenuInfo.longValue() <= 0) {
				throw BmpBizException.DB_INSERT_RESULT_0;
			}
		}
		//判断同步锁
		if(null == addXbdunSysMenuInfo)throw BizException.DB_INSERT_RESULT_0;
		return addXbdunSysMenuInfo;
	}

	/**
	* @Title: getSysMenu
	* @Description: 根据机构ID查询机构信息
	* @param orgId	机构ID
	* @return SysMenuResponse    返回类型
	* @throws
	 */
	public SysMenuResponse getSysMenu(long id)throws Exception{
		if (id <= 0 ) throw BizException.PARAM_CHKE_FAIL.newInstance("菜单ID不能小于等于零");
		
		XbdunSysMenuDo xbdunSysMenuById = sysMenuMapper.getXbdunSysMenuById(id);
		if ( null == xbdunSysMenuById ) {
			throw BizException.DB_SELECTONE_IS_NULL;
		}
		
		// 资源Copy
		SysMenuResponse response = new SysMenuResponse();
		BeanUtils.copyProperties(response, xbdunSysMenuById);
		return response;
	}

	/**
	* @Title: modifySysMenu
	* @Description: 修改菜单信息
	* @param request	修改的菜单信息
	* @throws Exception
	 */
	@Transactional
	public void modifySysMenu(SysMenuRequest request)throws Exception{
		XbdunSysMenuDo menu = sysMenuMapper.getXbdunSysMenuByCode(request.getCode());
		if (menu == null) {
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("修改的菜单不存在!");
		}
		HashMap<String, Object> param = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(request.getName())&&!request.getName().equals(menu.getName())) {
			param.put("name", request.getName());
		}
		if(StringUtils.isNotBlank(request.getHit())&&!request.getHit().equals(menu.getHit())){
			param.put("hit", request.getHit());
		}
		//页面和按钮才能修改url
		if(menu.getMenuType()==SysMenuTypeEnum.CATALOG.getKey()){
			if (StringUtils.isNotBlank(request.getUrl())){
				throw BizException.ERROR.newInstance("修改失败,目录不能设置链接");
			}
		}else if(menu.getMenuType()==SysMenuTypeEnum.PAGE.getKey()){
			//页面必须有url
			if (StringUtils.isNotBlank(request.getUrl())&&!request.getUrl().equals(menu.getUrl())){
				param.put("url", request.getUrl());
			}else if(StringUtils.isBlank(request.getUrl())){
				throw BizException.ERROR.newInstance("修改失败,页面必需存在菜单链接;");
			}
		}else if(menu.getMenuType()==SysMenuTypeEnum.BUTTON.getKey()){
			//按钮的url可有可无
			if (!request.getUrl().equals(menu.getUrl())){
				param.put("url", request.getUrl());
			}
		}
		if(!request.getIcoUrl().equals(menu.getIcoUrl())){
			param.put("icoUrl", request.getIcoUrl());
		}
		if(StringUtils.isNotBlank(request.getTarget())&&!request.getTarget().equals(menu.getTarget())){
			param.put("target", request.getTarget());
		}
		if(request.getEnable()!=menu.getEnable()){
			param.put("enable", request.getEnable());
		}
		if(request.getBlDisplay()!=menu.getBlDisplay()){
			param.put("blDisplay", request.getBlDisplay());
		}
		if(param.isEmpty()) {
			throw BizException.ERROR.newInstance("未做任何修改");
		}
		
		HashMap<String, Object> where = new HashMap<String, Object>();
		where.put("code", request.getCode());
		where.put("version", menu.getVersion());
		
		if (0==sysMenuMapper.updateDynXbdunSysMenu(param, where)) {
			param.clear();
			where.clear();
			param = null;
			where = null;
			throw BizException.DB_UPDATE_RESULT_0.newInstance("系统繁忙,更新菜单失败!");
		}
		param.clear();
		where.clear();
		param = null;
		where = null;
	}


	/**
	* @Title: queryTreeMenu
	* @Description: 查询所选机构的授权菜单树
	* @param orgCode	所选机构的机构Code
	* @param org		当前操作用户机构Code
	* @throws Exception
	 */
	public List<TreeNodeResponse> queryGrantMenu(long orgCode,Client client) throws Exception {
		List<TreeNodeResponse>  result  = null;
		List<MenuNodeDto> list = null;
		Long agetOrgCode = sysOrgBiz.getAgentOrgCode();
		//如果是平台管理员和代理机构，读取所有菜单并且选中当前机构的权限
		if(UserRolesEnums.isXbdAdmin(client.getRoleId())||(agetOrgCode!=null&&agetOrgCode==client.getOrgCode())){
			list = sysMenuMapper.queryAllMenu(orgCode);
		}else{
			//机构所拥有的菜单
			list = sysMenuMapper.querySelfOrgMenu(orgCode, null);
		}
		
//		if(UserRolesEnums.isXbdAdmin(client.getRoleId())){
//			list = sysMenuMapper.queryAllMenu(orgCode);
//		}else if(agetOrgCode!=null&&agetOrgCode.longValue()==client.getOrgCode()){
//			//如果是超级管理员，那么他应该拥有所有权限菜单，且
//			if(UserRolesEnums.isSupperAdmin(client.getRoleId())||UserRolesEnums.isAdmins(client.getRoleId())){
//				list = sysMenuMapper.queryAgentOrgMenu(orgCode,new Long[]{SysMenuConst.MENU_SETTING,SysMenuConst.MENU_SYS_ROLE_TRAN});
//			}else{
//				//一般机构使用
//				list = sysMenuMapper.queryOrgMenu(orgCode,client.getOrgCode(),new Long[]{SysMenuConst.MENU_SETTING,SysMenuConst.MENU_SYS_ROLE_TRAN,SysMenuConst.MENU_SYS_INFO,SysMenuConst.MENU_SYS_POWER});
//			}
//		}else{
//			//一般机构查看自己的权限
//			list = sysMenuMapper.querySelfOrgMenu(orgCode,SysMenuConst.MENU_SETTING+","+SysMenuConst.MENU_SYS_ROLE_TRAN+","+SysMenuConst.MENU_SYS_INFO+","+SysMenuConst.MENU_SYS_POWER+","+SysMenuConst.MENU_SYS_ROLE_TRAN);
//		}
		if(!CollectionUtils.isEmpty(list)){
			result = new ArrayList<TreeNodeResponse>();
			TreeNodeResponse infoRes = null;
			try{
				for(MenuNodeDto info : list){
					infoRes = new TreeNodeResponse();
					infoRes.setId(info.getId());
					infoRes.setPId(StringUtils.defaultIfBlank(info.getpId(),"0"));
					infoRes.setName(info.getName());
					infoRes.setTitle(info.getTitle());
					infoRes.setChecked(info.getChecked());
					result.add(infoRes);
				}
			}catch(Exception e){
				log.error("查询菜单转换失败",e);
			}finally{
				list.clear();
				list = null;	
			}
			
		}
		return result;
	}

	public List<TreeNodeResponse> queryMenuTree(long code,Client client)throws Exception {
		if(!UserRolesEnums.isXbdAdmin(client.getRoleId())) {
			throw BizException.POWER_FAIL.newInstance("对不起您当前权限不足,不能查看平台菜单");
		}
		List<TreeNodeResponse>  result  = null;
		List<MenuNodeDto> list = sysMenuMapper.queryAllMenuTree(code);
		if(!CollectionUtils.isEmpty(list)){
			result = new ArrayList<TreeNodeResponse>();
			TreeNodeResponse infoRes = null;
			try{
				for(MenuNodeDto info : list){
					infoRes = new TreeNodeResponse();
					infoRes.setId(info.getId());
					infoRes.setPId(StringUtils.defaultIfBlank(info.getpId(),"0"));
					infoRes.setName(info.getName());
					infoRes.setTitle(info.getTitle());
					infoRes.setType(info.getType());
					result.add(infoRes);
				}
				infoRes = new TreeNodeResponse();
				//创建根目录
				infoRes.setId("0");
				infoRes.setPId("00");
				infoRes.setName("根目录");
				infoRes.setTitle("根目录");
				infoRes.setType(SysMenuTypeEnum.CATALOG.getKey());
				result.add(infoRes);
			}catch(Exception e){
				log.error("查询菜单转换失败",e);
			}finally{
				list.clear();
				list = null;	
			}
		}
		return result;
	}

	public List<SysMenuResponse> getAllPlatByMenu(Client client)throws Exception {
		if(!UserRolesEnums.isXbdAdmin(client.getRoleId())) {
			throw BizException.POWER_FAIL.newInstance("对不起您当前权限不足,不能查看平台菜单");
		}
		List<SysMenuResponse>  result  = null;
		List<MenuPlatDto> list = sysMenuMapper.getAllPlatByMenu();
		if(!CollectionUtils.isEmpty(list)){
			result = new ArrayList<SysMenuResponse>();
			SysMenuResponse infoRes = null;
			try{
				for(MenuPlatDto info : list){
					infoRes = new SysMenuResponse();
					infoRes.setId(info.getId());
					infoRes.setCode(info.getCode());
					infoRes.setName(info.getName());
					infoRes.setHit(info.getHit());
					result.add(infoRes);
				}
			}catch(Exception e){
				log.error("查询菜单中平台转换失败",e);
			}finally{
				list.clear();
				list = null;	
			}
		}
		return result;
	}
	
	public List<PlatResponse> getAllPlat(Client client) {
		if(!UserRolesEnums.isXbdAdmin(client.getRoleId())) {
			throw BizException.POWER_FAIL.newInstance("对不起您当前权限不足,不能查看平台菜单");
		}
		List<PlatResponse>  result  = null;
		List<PlatformInfoDto> list = sysMenuMapper.getAllPlat();
		if(!CollectionUtils.isEmpty(list)){
			result = new ArrayList<PlatResponse>();
			PlatResponse infoRes = null;
			try{
				for(PlatformInfoDto info : list){
					infoRes = new PlatResponse();
					infoRes.setPlatCode(info.getPlatCode());
					infoRes.setPlatName(info.getPlatName());
					infoRes.setPlatDescrip(info.getPlatDescrip());
					result.add(infoRes);
				}
			}catch(Exception e){
				log.error("查询平台转换失败",e);
			}finally{
				list.clear();
				list = null;	
			}
		}
		return result;
	}

	public SysMenuResponse getMenuInfo(Long code, Client client)throws Exception {
		XbdunSysMenuDo xbdunSysMenuById = sysMenuMapper.getXbdunSysMenuByCode(code);
		if ( null == xbdunSysMenuById ) {
			throw BizException.DB_SELECTONE_IS_NULL;
		}
		// 资源Copy
		SysMenuResponse response = new SysMenuResponse();
		BeanUtils.copyProperties(response, xbdunSysMenuById);
		return response;
	}

	public void deleteSysMenu(Long code) throws Exception {
		//是否存在子菜单
		Long count = sysMenuMapper.getChildMenu(code);
		if (count!=1){
			if(count==0){
				throw BizException.DB_SELECTONE_IS_NULL.newInstance("删除失败,菜单不存在!");
			}else{
				throw BizException.DB_UPDATE_RESULT_0.newInstance("删除失败,该菜单下还存在子菜单");
			}
		}
		//查询当前菜单使用的次数
		Long cnt = sysMenuMapper.getMenuUsedCount(code);
		if(cnt==null || cnt.longValue()!=0) {
			throw BizException.DB_UPDATE_RESULT_0.newInstance("删除失败,原因是当前菜单正在被使用");
		}
		//删除企业被授权的菜单项
		sysMenuMapper.deleteOrgMenuByCode(code);
		//删除菜单表
		sysMenuMapper.deleteMenuByCode(code);
	}
	
	
	
	
}